package cn.aishua.ui.myKaka;

import org.apache.http.HttpResponse;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import cn.aishua.network.HttpRequestUtil;
import cn.aishua.ui.SplashActivity;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.util.FormatConverter;
import cn.aishua.util.Utils;

import cn.aishua.R;

public class CreditExchangeActivity
    extends Activity
{
    // page header widgets
    private ImageView ivLeftBtn;
    private ImageView ivRightBtn;
    private TextView tvTitile;

    public final static String EXTRA_MSG_AVAILABLE_CREDITS = "EXTRA_MSG_AVAILABLE_CREDITS";
    public final static String EXTRA_MSG_UNAVAILABLE_CREDITS = "EXTRA_MSG_UNAVAILABLE_CREDITS";

    public final static String EXTRA_MSG_EXCHANGE_CREDITS = "EXTRA_MSG_EXCHANGE_CREDITS";
    public final static String EXTRA_MSG_AMCOUNTS = "EXTRA_MSG_AMCOUNTS";

    private TextView tvAvailableCredits;
    private TextView tvUnavailableCredits;
    private TextView tvBank;
    private TextView tvType;
    private TextView tvNumber;
    private ImageView ivBankIcon;

    private EditText etCredit;
    private TextView tvAmount;

    private String alertMsg;

    private int credit; // available credit

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.my_kaka_credit_exchange );
        initPageHeader();
        initiate();
    }

    private void initPageHeader()
    {
        // left button
        ivLeftBtn = (ImageView) findViewById( R.id.page_header_iv_left_btn );
        ivLeftBtn.setImageResource( R.drawable.btn_back );
        ivLeftBtn.setOnClickListener( new OnClickListener()
        {

            @Override
            public void onClick( View v )
            {
                onBackPressed();
            }
        } );

        // title
        tvTitile = (TextView) findViewById( R.id.page_header_tv_title );
        tvTitile.setText( "积分兑换" );

        // right button 
        ivRightBtn = (ImageView) findViewById( R.id.page_header_iv_right_btn );
        ivRightBtn.setVisibility( View.GONE );
    }

    private void initiate()
    {
        tvAmount = (TextView) findViewById( R.id.my_kaka_credit_exchange_amount );

        etCredit = (EditText) findViewById( R.id.my_kaka_credit_exchange_credit );
        //        etCredit.setText( "0" );
        etCredit.setOnFocusChangeListener( new OnFocusChangeListener()
        {

            public void onFocusChange( View v, boolean hasFocus )
            {
                if( !hasFocus )
                {
                    Log.d( "CreditExchangeActivity", "view is: " + v.getClass().getSimpleName() );
                    String strCredit = etCredit.getText().toString();

                    // credit to be exchanged must be larger than 5000
                    int intCredit = FormatConverter.toInt( strCredit );
                    if( intCredit < 5 )
                        etCredit.setText( "5" );
                }

            }
        } );
        etCredit.addTextChangedListener( new TextWatcher()
        {

            public void onTextChanged( CharSequence s, int start, int before, int count )
            {
            }

            public void beforeTextChanged( CharSequence s, int start, int count, int after )
            {
            }

            public void afterTextChanged( Editable s )
            {
                if( !"".equals( s.toString() ) )
                {
                    int cashing = Integer.valueOf( s.toString() ) * 10 - 2;
                    if( cashing < 0 )
                        cashing = 0;
                    tvAmount.setText( "" + cashing );
                }
                else
                {
                    tvAmount.setText( "0" );
                }

            }
        } );

        tvAvailableCredits = (TextView) findViewById( R.id.my_kaka_credit_exchange_tv_available_credits );
        tvUnavailableCredits = (TextView) findViewById( R.id.my_kaka_credit_exchange_tv_unavailable_credits );

        tvBank = (TextView) findViewById( R.id.my_kaka_credit_exchange_bank );
        tvType = (TextView) findViewById( R.id.my_kaka_credit_exchange_type );
        tvNumber = (TextView) findViewById( R.id.my_kaka_credit_exchange_number );
        ivBankIcon = (ImageView) findViewById( R.id.my_kaka_credit_exchange_iv_bank_icon );

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if( !SplashActivity.MAIN_IS_IN_STACK )
        {
            finish();
            return;
        }

        new DataExchangeAsyncTask( this, "获取兑换信息" )
        {

            @Override
            protected HttpResponse sendRequest( String... params )
            {
                return HttpRequestUtil.getInstance().getCashingCredit();
            }

            @Override
            protected void handleSuccResponse( String strJson ) throws Exception
            {
                /**
                 * {"card_info":{"usable_credit":0,"card_number":"23568007","locked_credit":0,
                 * "bank_display_name":"招商银行","mobile":"18602863453"}}
                 */

                JSONObject jsonObj = new JSONObject( strJson );

                if( jsonObj.has( "msg" ) ) // user hasn't set exchange card
                {
                    tvAvailableCredits.setText( FormatConverter.getJsonString( jsonObj, "usable_credit", "0" ) );
                    tvUnavailableCredits.setText( FormatConverter.getJsonString( jsonObj, "locked_credit", "0" ) );
                    alertMsg = FormatConverter.getJsonString( jsonObj, "msg", "亲，请设置兑现银行卡先" );
                }
                else
                {
                    JSONObject cardInfo = jsonObj.getJSONObject( "card_info" );

                    credit = cardInfo.getInt( "usable_credit" );
                    tvAvailableCredits.setText( "" + credit );
                    tvUnavailableCredits.setText( "" + cardInfo.getInt( "locked_credit" ) );
                    String bank = cardInfo.getString( "bank_display_name" );
                    tvBank.setText( bank );
                    tvType.setText( "储蓄卡" );
                    tvNumber.setText( FormatConverter.toCardNumFormat( cardInfo.getString( "card_number" ) ) );
                    ivBankIcon.setImageResource( Utils.getIconResId( getApplicationContext(), bank ) );
                }
            }
        }.execute();

    }

    public void minus( View view )
    {
        String strCredit = etCredit.getText().toString();
        if( !"".equals( strCredit ) )
        {
            int intCredit = Integer.valueOf( strCredit );
            if( --intCredit >= 5 )
            {
                etCredit.setText( "" + intCredit );
            }
        }
        else
        {
            etCredit.setText( "5" );
        }
    }

    public void plus( View view )
    {
        String strCredit = etCredit.getText().toString();
        if( !"".equals( strCredit ) )
        {
            int intCredit = Integer.valueOf( strCredit );

            etCredit.setText( "" + ( ++intCredit ) );
        }
        else
        {
            etCredit.setText( "1" );
        }
    }

    public void next( View view )
    {
        if( alertMsg != null )
        {
            Toast.makeText( this, alertMsg, Toast.LENGTH_SHORT ).show();
            return;
        }

        Intent toCreditExchangeNext = new Intent( this, CreditExchangeNextActivity.class );
        String inputCredit = etCredit.getText().toString();

        if( FormatConverter.toInt( inputCredit ) < credit )
        {
            toCreditExchangeNext.putExtra( EXTRA_MSG_AVAILABLE_CREDITS, "" + credit );
            toCreditExchangeNext.putExtra( EXTRA_MSG_UNAVAILABLE_CREDITS, tvUnavailableCredits.getText().toString() );

            toCreditExchangeNext.putExtra( EXTRA_MSG_EXCHANGE_CREDITS, inputCredit + "000" );
            toCreditExchangeNext.putExtra( EXTRA_MSG_AMCOUNTS, tvAmount.getText().toString() );
            startActivity( toCreditExchangeNext );
        }
        else
        {
            Toast.makeText( this, "您的可用积分不足" + inputCredit + "000，请重新输入", Toast.LENGTH_SHORT ).show();
        }

    }

}
